﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using LS.Api.Helper;
using LS.Api.Models;
using LS.Common;
using LS.Cores;
using LS.Entitys;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

namespace LS.Api.Controllers
{
    /// <summary>
    /// 授权相关
    /// </summary>
    public class AuthController : APIBaseController
    {
        ISysUser userService;
        public AuthController(ISysUser repositoryUser)
        {
            userService = repositoryUser;
        }
        ///// <summary>
        ///// 获取token
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public IHttpActionResult Token(AuthInput input)
        //{
        //    ApiJsonResult result = null;
        //    //这是是获取用户名和密码的
        //    if (input.AuthName == "sxgwapi" && input.AuthKey == "sx123456")
        //    {
        //        AuthInfo info = new AuthInfo
        //        {
        //            UserName = "sxgwapi",
        //            UserId = 2020888,
        //            LoginType = 1,
        //            ExpiryDateTime = DateTime.Now.AddHours(2).AddMinutes(1)
        //        };
        //        try
        //        {
        //            string secret = ConfigurationManager.AppSettings["SecureKey"];//口令加密秘钥
        //            //secret需要加密
        //            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
        //            IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
        //            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
        //            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//JWT编码
        //            var token = encoder.Encode(info, secret);//生成令牌
        //            result = new ApiJsonResult(ApiResult.Success, "获取成功", new { token, expires = DateTime.Now.AddHours(2) });
        //        }
        //        catch (Exception ex)
        //        {
        //            Log4NetHelper.GetLogger("Global").Error(ex);
        //            result = new ApiJsonResult(ApiResult.Fail, ex.Message.ToString());
        //        }
        //    }
        //    else
        //    {
        //        result = new ApiJsonResult(ApiResult.Fail, "未查询到授权信息");
        //    }
        //    return ApiJson(result);
        //}

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet, HiddenApi]
        public HttpResponseMessage GetVerCode()
        {
            try
            {
                var helper = new ValidateCodeHelper();
                var code = helper.RandomCode(4);
                var data = helper.CreateGraphic(code, 2);

                SessionHelper.SetSession("imgCode", code);

                //从图片中读取流
                var resp = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(data)
                };
                resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                return resp;
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.NotFound,
                    Content = new StringContent("404")
                };
            }
        }

        /// <summary>
        /// 账号密码登录
        /// </summary>
        /// <param name="input">登录实体</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult Login(LoginInput input)
        {
            if (input == null || string.IsNullOrEmpty(input.UserName) || string.IsNullOrEmpty(input.Password))
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "用户名和密码不能为空"));
            }
            //if (string.IsNullOrEmpty(input.VerCode))
            //{
            //    return ApiJson(new ApiJsonResult(ApiResult.Fail, "验证码不能为空"));
            //}
            //var imgCode = SessionHelper.GetSession("imgCode");
            //if (imgCode == null)
            //{
            //    return ApiJson(new ApiJsonResult(ApiResult.Fail, "验证码已过期"));
            //}
            //if (imgCode.ToString().ToLower() != input.VerCode.ToLower())
            //{
            //    return ApiJson(new ApiJsonResult(ApiResult.Fail, "验证码错误"));
            //}
            string md5Pwd = input.Password;
            //string md5Pwd = DESEncryptHelper.GetMd5Hash(input.Password);
            var user = userService.Login(input.UserName, md5Pwd);
            if (user == null)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "用户名或密码错误"));
            }
            if (user.IsDel == 1)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "您登录的账号已删除"));
            }
            if (user.Isenable == null || !user.Isenable.Value)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "您的账号暂未启用，请联系管理员处理"));
            }
            if (user.UserStatus != 1)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "您的账号正在审核中，请您耐心等待"));
            }
            if (user.UserType != 2)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "您不是企业用户，暂时无法登录"));
            }
            AuthInfo info = new AuthInfo
            {
                UserName = user.RealName,
                UserId = user.Id,
                LoginType = 2,
                ExpiryDateTime = DateTime.Now.AddHours(2).AddMinutes(1)
            };
            try
            {
                string secret = ConfigurationManager.AppSettings["SecureKey"];//口令加密秘钥
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
                IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//JWT编码
                var token = encoder.Encode(info, secret);//生成令牌
                return ApiJson(new ApiJsonResult(ApiResult.Success, "登录成功", new { user, userToken = token, tokenExpires = DateTime.Now.AddHours(2) }));
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
            }
        }

        /// <summary>
        /// 账号注册
        /// </summary>
        /// <param name="input">注册实体</param>
        /// <returns></returns>
        [HttpPost, HiddenApi]
        public IHttpActionResult Register(RegisterInput input)
        {
            //这是是获取用户名和密码的
            if (input == null)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "提交信息不能为空"));
            }
            if (string.IsNullOrEmpty(input.CompanyName) || string.IsNullOrEmpty(input.Contacts) || string.IsNullOrEmpty(input.ContactTel))
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "企业及联系人信息不能为空"));
            }
            if (string.IsNullOrEmpty(input.UserName) || string.IsNullOrEmpty(input.Password))
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "用户名和密码不能为空"));
            }
            if (input.Password != input.ConfirmPassword)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "密码和确认密码不一致"));
            }
            if (string.IsNullOrEmpty(input.VerCode))
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "验证码不能为空"));
            }
            var imgCode = SessionHelper.GetSession("imgCode");
            if (imgCode == null)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "验证码已过期"));
            }
            if (imgCode.ToString().ToLower() != input.VerCode.ToLower())
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "验证码错误"));
            }
            try
            {
                if (userService.ExistAccount(input.UserName))
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, "用户名已存在，请换其他用户名试试"));
                }
                var user = new SysUserEntity();
                user.UserName = input.UserName;
                user.UserPwd = input.Password;
                //user.UserPwd = DESEncryptHelper.GetMd5Hash(input.Password);
                user.RealName = input.Contacts;
                user.Sex = 0;
                user.Avatar = "";
                user.Mobile = input.ContactTel;
                user.Email = "";
                user.Isenable = true;
                user.UserType = 2;
                user.RoleCode = "";
                user.UserStatus = 0;
                user.IsDel = 0;
                user.CreateDate = DateTime.Now;
                user.CreateBy = "";
                user.CompanyName = input.CompanyName;
                var ret = userService.Insert(user);
                if (ret > 0)
                {
                    //CmsCompanyEntity company = new CmsCompanyEntity();
                    //company.CompanyName = input.CompanyName;
                    //company.Contacts = input.Contacts;
                    //company.ContactTel = input.ContactTel;
                    //company.CompStatus = 1;
                    //company.FlowID = 0;
                    //company.FlowStatus = 0;
                    //company.IsDel = 0;
                    //company.CreateDate = DateTime.Now;
                    //company.CreateBy = ret.ToString();
                    //var companyid = companyService.Insert(company);
                    //user.CompanyId = companyid;

                    //userService.Update(user);

                    return ApiJson(new ApiJsonResult(ApiResult.Success, "注册成功", new { user }));
                }
                else
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, "提交失败，请重试"));
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
            }
        }

        /// <summary>
        /// 验证token 是否正确并返回对象
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HiddenApi]
        public IHttpActionResult VerifyToken(string token)
        {
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    //string secureKey = System.Configuration.ConfigurationManager.AppSettings["SecureKey"];
                    string secret = ConfigurationManager.AppSettings["SecureKey"];
                    //secret需要加密
                    IJsonSerializer serializer = new JsonNetSerializer();
                    IDateTimeProvider provider = new UtcDateTimeProvider();
                    IJwtValidator validator = new JwtValidator(serializer, provider);
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

                    var json = decoder.DecodeToObject<AuthInfo>(token, secret, true);
                    if (json != null)
                    {
                        //判断口令过期时间
                        if (json.ExpiryDateTime < DateTime.Now)
                        {
                            return ApiJson(new ApiJsonResult(ApiResult.Fail, "token过期"));
                        }

                        return ApiJson(new ApiJsonResult(ApiResult.Success, "", json));
                    }

                }
                catch (Exception ex)
                {
                    Log4NetHelper.GetLogger("Global").Error(ex);
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
                }
            }
            return ApiJson(new ApiJsonResult(ApiResult.Fail, "未检测到授权信息"));

        }
    }
}
